<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>贪吃蛇小游戏</title>

    <style>
        body {
            margin: 0px;
            padding: 0px;
        }

        #main {
            margin: 100px;
        }

        .btn {
            width: 100px;
            height: 40px;
        }
    </style>
</head>

<body>
    <div id="main">
        <input class="btn" type="button" value="开始游戏" id="begin" />
        <input class="btn" type="button" value="暂停游戏" id="pause" />
        <script>
            var main = document.getElementById('main');
            var showcanvas = true;//是否开启画布小格子
            /**
             * 地图对象构造方法
             * @param atom 单个原子的正方形atom为边长
             * @param xnum 横向原子的数量
             * @param ynum 纵向原子的数量
             * @constructor
             * */
            function Map(atom, xnum, ynum) {
                this.atom = atom;     //20*20
                this.xnum = xnum;
                this.ynum = ynum;

                this.canvas = null;

                //创建画布的方法
                this.create = function () {
                    this.canvas = document.createElement('div');
                    this.canvas.style.cssText = "position:relative;top:40px;border:1px solid darkred;background:#FAFAFA";
                    this.canvas.style.width = this.atom * this.xnum + 'px';  //画布额宽
                    this.canvas.style.height = this.atom * this.ynum + 'px';  //画布的高
                    main.appendChild(this.canvas);

                    if (showcanvas) {
                        for (var y = 0; y < ynum; y++) {
                            for (var x = 0; x < xnum; x++) {
                                var a = document.createElement('div');
                                a.style.cssText = "border:1px solid yellow";
                                a.style.width = this.atom + 'px';
                                a.style.height = this.atom + 'px';
                                a.style.backgroundColor = "green";
                                this.canvas.appendChild(a);
                                a.style.position = 'absolute';
                                a.style.left = x * this.atom + 'px';
                                a.style.top = y * this.atom + 'px';
                            }
                        }
                    }
                }
            }
            

            var map = new Map(20, 40, 20);
            map.create();

            var timer;  //变量可以提升

            document.getElementById("begin").onclick = function () {
                clearInterval(timer);
                timer = setInterval(function () {

                }, 300);
            }

            document.getElementById('pause').onclick = function () {
                clearInterval(timer);
            }
        </script>
    </div>
</body>

</html>